package com.songcha.library_business.proxy.database

import com.songcha.library_common.util.LogUtil
import com.songcha.library_database_douyue.manager.GreenDaoManager
import com.songcha.library_database_douyue.bean.BookSearchHistoryBean
import com.songcha.library_database_douyue.greendao.BookSearchHistoryBeanDao
import org.greenrobot.greendao.query.WhereCondition

class BookSearchHistoryDaoManager {
    companion object{
        const val MAX_HISTORY_SIZE=10

        @JvmStatic
        fun addSearchHistory(keyword:String){
            try{
                val searchHistoryDao= GreenDaoManager.getInstance().bookSearchHistoryDao
                //if size>=10,del size-9,insert
                val qb=searchHistoryDao.queryBuilder()
                val list=qb.list()
                if(list.size>=MAX_HISTORY_SIZE){
                    val delSize=list.size-MAX_HISTORY_SIZE-1
                    qb.where(
                        WhereCondition.StringCondition("_id in " +
                                "(select _id from ${BookSearchHistoryBeanDao.TABLENAME} order by _id limit $delSize)"))
                    qb.buildDelete().executeDeleteWithoutDetachingEntities()
                }
                val bean=
                    BookSearchHistoryBean()
                bean.title=keyword
                searchHistoryDao.insertOrReplace(bean)
            }catch (e:Exception){
                e.printStackTrace()
                LogUtil.log("保存搜索历史异常")
            }
        }

        @JvmStatic
        fun getSearchHistoryList():MutableList<BookSearchHistoryBean>{
            try{
                val searchHistoryDao= GreenDaoManager.getInstance().bookSearchHistoryDao
                val qb=searchHistoryDao.queryBuilder()
                qb.orderDesc(BookSearchHistoryBeanDao.Properties.Id)
                qb.limit(MAX_HISTORY_SIZE)
                val list=qb.list()
                return list
            }catch (e:Exception){
                e.printStackTrace()
                return mutableListOf()
            }
        }

        @JvmStatic
        fun delAllSearchHistory(){
            try{
                val searchHistoryDao= GreenDaoManager.getInstance().bookSearchHistoryDao
                searchHistoryDao.deleteAll()
            }catch (e:Exception){
                e.printStackTrace()
            }
        }
    }
}